import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  KeyboardAvoidingView,
  Platform,
  TouchableWithoutFeedback,
  Keyboard,
  Alert,
} from "react-native";
import useHideTabBar from '../utils/useHideTabBar';
import { useNavigation } from '@react-navigation/native';
import theme from '../utils/theme';
import API from '../Network/Api';
import { showToast } from '../utils/toastUtils';
import Toast from 'react-native-toast-message';
import { CustomText } from "../customview/CustomText";
import { normalize } from "../utils/commonUtils";
import Api from "../Network/Api";

let verifyCode = '';

const RegistrationPage = () => {
  const [phoneNumber, setPhoneNumber] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [payPassword, setPayPassword] = useState('');
  const [invitationCode, setInvitationCode] = useState('');
  const [countdown, setCountdown] = useState(0); // 新增：倒计时状态
  const navigation = useNavigation();
  let hasManuallyGoneBack = false;
  useHideTabBar(navigation);

  // 监听返回按钮点击事件
  navigation.addListener('beforeRemove', () => {
    // 用户手动点击返回按钮时，设置标志变量为 true
    hasManuallyGoneBack = true;
  });

  // 新增：倒计时逻辑
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => {
        setCountdown(countdown - 1);
      }, 1000);
      return () => clearTimeout(timer);
    }
  }, [countdown]);

  const handleSendVerificationCode = () => {
    if (countdown > 0) return; // 如果正在倒计时，不允许再次发送
    if (!phoneNumber) {
      showToast({
        text2: '请输入手机号',
      });
      return;
    }
    if (phoneNumber.length !== 11) {
      showToast({
        text2: '手机号格式错误，请确认11位或是否有空格！',
      });
      return;
    }
    // 开始倒计时
    setCountdown(60);
    Api.getVerifyCode()
      .then(response => {
        if (response.resultCode === '1') {
          showToast({
            text2: '验证码：' + response.data.verifyCode,
            visibilityTime: 3000,
          });
          verifyCode = response.data.verifyCode;
        } else {
          showToast({
            text2: response.showMsg,
          });
          setCountdown(0); // 发送失败，停止倒计时
        }
      })
      .catch(error => {
        showToast({
          text2: '验证码获取失败，请联系管理员！',
        });
        setCountdown(0); // 发送失败，停止倒计时
      });
  };

  const handleRegister = () => {
    if (verifyCode === '' || verifyCode !== verificationCode) {
      showToast({ text2: '验证码不正确！' });
      return;
    }
    if (password !== confirmPassword) {
      showToast({ text2: '两次密码输入不匹配！' });
      return;
    }
    API.registerReq(
      phoneNumber,
      verificationCode,
      password,
      payPassword,
      invitationCode,
    )
      .then(response => {
        console.log('success', response);
        if (response.resultCode === '1') {
          hasManuallyGoneBack = false;
          showToast({
            text2: '注册成功！',
            visibilityTime: 1000,
          }).then(() => {
            if (!hasManuallyGoneBack) {
              navigation.goBack();
            }
          });
        } else if (response.data.errMsg) {
          showToast({
            type: 'error',
            text2: response.data.errMsg,
          });
        } else {
          showToast({
            type: 'error',
            text2: response.showMsg,
          });
        }
      })
      .catch(error => {
        console.log('error', error);
        showToast({
          type: 'error',
          text2: '注册失败！',
        });
      });
  };

  const dismissKeyboard = () => {
    Keyboard.dismiss();
  };

  return (
    <TouchableWithoutFeedback onPress={dismissKeyboard}>
      <KeyboardAvoidingView
        style={styles.container}
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 50}
        duration={300}
      >
        <TextInput
          allowFontScaling={false}
          style={styles.input}
          placeholder="请输入手机号"
          keyboardType="phone-pad"
          value={phoneNumber}
          onChangeText={(text) => setPhoneNumber(text)}
        />

        <View style={styles.verificationCodeContainer}>
          <TextInput
            allowFontScaling={false}
            style={[styles.input, { flex: 3 }]}
            placeholder="请输入验证码"
            keyboardType="phone-pad"
            value={verificationCode}
            onChangeText={(text) => setVerificationCode(text)}
          />
          <TouchableOpacity
            style={styles.sendCodeButton}
            onPress={handleSendVerificationCode}
            disabled={countdown > 0} // 倒计时期间禁用按钮
          >
            <CustomText style={styles.sendCodeButtonText}>
              {countdown > 0 ? `${countdown}s` : '发送'}
            </CustomText>
          </TouchableOpacity>
        </View>

        <TextInput
          allowFontScaling={false}
          style={styles.input}
          placeholder="请输入登录密码"
          secureTextEntry
          value={password}
          onChangeText={(text) => setPassword(text)}
        />

        <TextInput
          allowFontScaling={false}
          style={styles.input}
          placeholder="请再次输入登录密码"
          secureTextEntry
          value={confirmPassword}
          onChangeText={(text) => setConfirmPassword(text)}
        />

        <TextInput
          allowFontScaling={false}
          style={styles.input}
          placeholder="请输入支付密码"
          secureTextEntry
          value={payPassword}
          onChangeText={(text) => setPayPassword(text)}
        />

        <TextInput
          allowFontScaling={false}
          style={styles.input}
          placeholder="请输入邀请码（必填）"
          value={invitationCode}
          onChangeText={(text) => setInvitationCode(text)}
        />

        <TouchableOpacity style={styles.registerButton} onPress={handleRegister}>
          <CustomText style={styles.registerButtonText}>立即注册</CustomText>
        </TouchableOpacity>
        <Toast />
      </KeyboardAvoidingView>
    </TouchableWithoutFeedback>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f0f0f0',
    padding: 20,
  },
  input: {
    width: '100%',
    height: 45,
    backgroundColor: '#fff',
    borderRadius: 20,
    paddingHorizontal: 15,
    marginBottom: 15,
  },
  verificationCodeContainer: {
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  sendCodeButton: {
    flex: 1,
    backgroundColor: theme.colors.primary,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 10,
    marginTop: 3,
    height: 38,
  },
  sendCodeButtonText: {
    color: '#fff',
    fontWeight: 'bold',
  },
  registerButton: {
    width: '70%',
    height: 40,
    backgroundColor: theme.colors.primary,
    borderRadius: 20,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 40,
  },
  registerButtonText: {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: normalize(16),
  },
});

export default RegistrationPage;
